package model;

import java.io.File;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanTable;

import beans.Bookmark;
import beans.User;
/*
 *  Course: S09-15437 - WEB APPLICATION DEVELOPMENT 
 * 	Name: Jiale Huang
 * 	Andrew ID: jialeh
 * 	Date: 2/23/2009
 *  Assignment: Hw4
 */

public class Model {
	private BookmarkDAO bookmarkDAO;
	private UserDAO  userDAO;

	public Model(ServletConfig config) throws ServletException {
		try {
			String jdbcDriver = config.getInitParameter("jdbcDriverName");
			String jdbcURL    = config.getInitParameter("jdbcURL");
			BeanTable.useJDBC(jdbcDriver,jdbcURL);
			
			userDAO  = new UserDAOFactoryImpl();
			bookmarkDAO = new BookmarkDAOFactoryImpl();
			
			if(userDAO.getUsers()== null || userDAO.getUsers().size() == 0 )
				buildRows();
			
		} catch (DAOException e) {
			throw new ServletException(e);
		}
	}
	
	public BookmarkDAO getBookmarkDAO() { return this.bookmarkDAO; }
	public UserDAO  getUserDAO()  { return this.userDAO;  }
	
	private void buildRows() throws ServletException{
				
		try {
			User user;
			Bookmark bookmark;
			
			String[] userEmails = {"abc@gmail.com", "yellowcola@yahoo.com", "jle@cmu.edu"}; 
			String[] bookmarks = {"www.google.com", "www.yahoo.com", "www.facebook.com", "www.myspace.com"};
			String[] userFName = {"Jiale", "Cool", "Jeffrey"};
			String[] userLName = {"Huang", "top", "Eppinger"};
			
			for(int i = 0; i < userEmails.length; i++){
			
				user = userDAO.create(userEmails[i]);
				user.setPassWord("1111");
				user.setFName(userFName[i]);
				user.setLName(userLName[i]);
				
				userDAO.update(user);
				
				for(int j = 0; j < bookmarks.length; j++){
					bookmark = new Bookmark(userEmails[i]);
					bookmark.setURL(bookmarks[j]);
					bookmark.setComment("horrible!!!");
					bookmark.setClickCount(0);					
					bookmarkDAO.create(bookmark);
				}			
			}			
			
		} catch (DAOException e) {
			throw new ServletException(e);
		}
	}
}

